/*
  File: RoleInterceptor.cs
  Author: rcrxy
  CreateTime: 2025/07/04 11:54

  Description:
*/

using Microsoft.EntityFrameworkCore.Diagnostics;
using StudentVideo.Common.Constants;
using StudentVideo.Data.Entities;
using StudentVideo.Helper;
using System.Text.Json;

namespace StudentVideo.Interceptors;

public class RoleInterceptor(RedisDbHelper redis): SaveChangesInterceptor {
   private readonly RedisDbHelper _redis = redis;

   public override async ValueTask<int> SavedChangesAsync(SaveChangesCompletedEventData eventData, int result, CancellationToken cancellationToken = default) {
      var context = eventData.Context;

      await _redis.SyncToRedis<RoleEntity>(context, new() {
         Create = Update,
         Update = Update,
         Delete = Delete
      });

      return await base.SavedChangesAsync(eventData, result, cancellationToken);
   }

   private async Task Update(RoleEntity role) {
      await _redis.Db.HashSetAsync(RedisKeys.Role, role.Id, JsonSerializer.Serialize(role));

      return;
   }

   private async Task Delete(RoleEntity role) {
      await _redis.Db.HashDeleteAsync(RedisKeys.Role, role.Id);

      return;
   }
}
